@extends('admin.main')
@section('head')
@section('head')
    @include('UEditor::head')
    <style>

        .choose-div :hover{
            background: #adda8f;
            color: #fff
        }
    </style>

    <script src="/static/citys/city.data-3.js" type="text/javascript"></script>
    <script src="/static/citys/jquery.citys.js" type="text/javascript"></script>
    <script charset="utf-8"
            src="https://map.qq.com/api/js?v=2.exp&key=RHHBZ-K26W6-CPISS-ENGXG-HVCRS-QJFQT&libraries=drawing,geometry,autocomplete,convertor"></script>
    <script type="text/javascript"
            src="https://3gimg.qq.com/lightmap/components/geolocation/geolocation.min.js"></script>
@endsection
@section('body')
    <div class="main-title">
        <h2>{{isset($info['id']) ? '编辑':'新增'}}用户</h2>
    </div>
    <div class="tab-wrap">
        <div class="tab-content">
            <form action="" method="post" class="form-horizontal">
                <!-- 基础 -->
                <div id="tab1" class="tab-pane in tab1">
                    <div class="form-item">
                        <label class="item-label">
                            用户姓名<span class="check-tips">（姓名不能为空）</span>
                        </label>
                        <div class="controls">
                            <input type="text" name="name" class="text input-large" placeholder=""
                                   value="{{isset($info['address']['name']) ? $info['address']['name'] : ''}}">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="item-label">
                            联系方式<span class="check-tips">（必填）</span>
                        </label>
                        <div class="controls">
                            <input type="text" name="mobile" class="text input-large"
                                   value="{{isset($info['address']['mobile']) ? $info['address']['mobile'] : ''}}">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="item-label">
                            用户类型<span class="check-tips"></span>
                        </label>
                        <div class="controls">
                            <label class="inline radio"><input type="radio" name="type" value="1"
                                                               @if(!isset($info['address']['type']) || $info['address']['type'] == 1) checked @endif>单位</label>
                            <label class="inline radio"><input type="radio" name="type" value="2"
                                                               @if(isset($info['address']['type']) && $info['address']['type'] == 2) checked @endif>家庭</label>
                        </div>
                    </div>
                    <div class="form-item" id="company" @if(isset($info['address']['type']) && ($info['address']['type'] != 1)) style="display: none"  @endif>
                        <label class="item-label">
                            单位名称<span class="check-tips">（必填）</span>
                        </label>
                        <div class="controls">
                            <input type="text" name="company_name" class="text input-large"
                                   value="{{isset($info['address']['company_name']) ? $info['address']['company_name'] : ''}}">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="item-label">
                            所属区域<span class="check-tips"></span>
                        </label>
                        <div class="controls">
                            <div id="area">
                                <select name="province"></select>
                                <select name="city"></select>
                                <select name="area"></select>
                            </div>
                            <input type="hidden" name="area_info" id="area_info"
                                   value="{{isset($info['address']['area_info']) ? $info['address']['area_info'] : ''}}">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="item-label">
                            地址<span class="check-tips">（地址不能为空）</span>
                        </label>
                        <div class="controls">
                            <input type="text" name="position_address" id='position_address' class="text input-large position_address" style="width: 550px;"
                                   placeholder=""
                                   value="{{isset($info['address']['position_address']) ? $info['address']['position_address'] : ''}}">
                        
                        </button>       
                        </div>
                    </div>
                    <div class="form-item" style="position: relative;">
                        <div style="width:50%;height:400px" id="container_map"></div>
                        <div class="choose-div" style="position: absolute;top: -0.5rem;left: 0;width: 18%;height: 400px;background: #fff;z-index: 99999;overflow: hidden;overflow-y: auto;display: none;">
                            
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="item-label">
                            门牌号<span class="check-tips">（地址不能为空）</span>
                        </label>
                        <div class="controls">
                            <input type="text" name="address" id='address' class="text input-large" style="width: 550px;"
                                   placeholder=""
                                   value="{{isset($info['address']['address']) ? $info['address']['address'] : ''}}">
                        </div>
                    </div>
                    <!-- 高级 -->
                    <div class="form-item">
                        <input type="hidden" name="id" value="{{isset($info['id']) ? $info['id'] : ''}}">
                        <input type="hidden" name="address_id" value="{{isset($info['address']['id']) ? $info['address']['id'] : ''}}">
                        <input type="hidden" name="area_position" id='area_position' value="{{isset($info['address']['area_position']) ? $info['address']['area_position'] : ''}}">
                        <input type="hidden" name="province" id="province_id" value="{{isset($info['address']['province_id']) ? $info['address']['province_id'] : ''}}">
                        <input type="hidden" name="city" id="city_id" value="{{isset($info['address']['city_id']) ? $info['address']['city_id'] : ''}}">
                        <input type="hidden" name="area" id="area_id" value="{{isset($info['address']['area_id']) ? $info['address']['area_id'] : ''}}">
                        <button type="submit" id="submit" class="btn submit-btn ajax-post"
                                target-form="form-horizontal">确 定
                        </button>
                        <button class="btn btn-return" onclick="javascript:history.back(-1);return false;">返 回</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
@endsection

@section('script')
    <script type="text/javascript">
        $('#area').citys({
            @if(isset($info['address']['area_id']))
            code:"{{$info['address']['area_id']}}",
            @endif
            required: false,
            nodata: 'disabled',
            onChange: function (data) {
                $('#area_info').val(data['province'] + ' ' + data['city'] + ' ' + data['area']);
            }
        });

        $('input[type=radio]').change(function () {
            var self = $(this);
            var type = self.val();
            if (type == 1) {
                $("#company").show();
            } else {
                $("#company").hide();
            }
        });

        var area_info = "{{isset($info) ? $info['address']['area_info'] : ''}}";
        var region ='';
        if(area_info != undefined && area_info != null && area_info != ''){
            region = area_info.split(' ')[1];
        }
        var latLng = "{{isset($info) ? $info['address']['area_position'] : ''}}";
        var addressDetail = "{{isset($info) ? $info['address']['area_info'] : ''}}" + "{{isset($info) ? $info['address']['position_address'] : ''}}" + "{{isset($info) ? $info['address']['address'] : ''}}";

        var geocoder, map,mubiao, circle ,marker ,info ,lat ,lng ,address ,name,center ,nearPost , range_height ,argument_range,province,city,area= null;

        
        if(latLng != undefined && latLng != null && latLng != ''){
            lat = latLng.split(',')[0];
            lng = latLng.split(',')[1];
            //调用初始化函数地图
            init();

        }else if (addressDetail !=undefined && addressDetail != null && addressDetail != '') {
            //地址和经纬度之间进行转换服务
            geocoder = new qq.maps.Geocoder({
                //设置服务请求成功的回调函数
                complete: function(result) {

                    lat = result.detail.location.lat;
                    lng = result.detail.location.lng;
                    latLng = lat+','+lng;
                    $('#area_position').val(latLng);
                    //调用初始化函数地图
                     init();

                },
                //若服务请求失败，则运行以下函数
                error: function() {
                    layer.msg('地址定位出错，请在地图上自行选择');
                }
            });
            //如果没有经纬度 那么 按照已有地址获取经纬度
            geocoder.getLocation(addressDetail);
        }else {

            lat='30.462959';
            lng = '114.419449';
            //调用初始化函数地图
            init();
        }

    
        var search_nearPost = '';
        //直接加载地图
        //初始化地图函数  自定义函数名init
        function init() {
            center = new qq.maps.LatLng(lat, lng);
            //定义map变量 调用 qq.maps.Map() 构造函数   获取地图显示容器
            map = new qq.maps.Map(document.getElementById("container_map"), {
                center: center,      // 地图的中心地理坐标。
                zoom:13                                                 // 地图的中心地理坐标。
            });

            marker = new qq.maps.Marker({
                //设置Marker的位置坐标
                position: center,
                //设置显示Marker的地图
                map: map
            });
            //设置Marker是否可以被拖拽，为true时可拖拽，false时不可拖拽，默认属性为false
            marker.setDraggable(false);
            //添加信息窗口
            info = new qq.maps.InfoWindow({
                map: map
            });
            //获取标记的可拖动属性
            info.open();
            info.setContent('<p style="color:  #25bdef">用户地址</p>');
            info.setPosition(marker.getPosition());


            geocoder = new qq.maps.Geocoder({
                complete : function(result){
                    marker.setMap(null);
                    info.setMap(null);
                    lat = result.detail.location.lat;
                    lng = result.detail.location.lng;
                    $('#area_position').val(lat+','+lng);
                    make_map(lat,lng);

                }
            });

            //绑定单击事件添加参数
            qq.maps.event.addListener(map, 'click', function(event) {
                marker.setMap(null);
                info.setMap(null);
                //根据获取的经纬度 得到具体地址
                make_map(event.latLng.getLat(),event.latLng.getLng());
                var latLng = new qq.maps.LatLng(event.latLng.getLat(), event.latLng.getLng());
                geocoder.getAddress(latLng);
                if(geocoder!=undefined && geocoder!=null && geocoder != ''){
                    //设置服务请求成功的回调函数
                    geocoder.setComplete(function(result) {
                        nearPost = result.detail;
                        province = nearPost.addressComponents.province;
                        city = nearPost.addressComponents.city;
                        area = (nearPost.addressComponents.district == undefined || nearPost.addressComponents.district == null || nearPost.addressComponents.district == '')?'':nearPost.addressComponents.district;
                        search_nearPost = nearPost.nearPois;
                        console.log(search_nearPost)
                        getAddressCode();
                        make_address_list(search_nearPost,2);
                        $('.choose-div').show();
                    });
                }
            });
        }

        function make_address_list(list,type) {
            if(list != undefined && list != null && list != ''){
                console.log(list)
                var tableContent = "";
                for(var i=0;i<list.length;i++){
                    var obj = list[i];
                    var detail = obj.name;
                    if(type == 1){
                        detail = obj.title;
                        //获取省市区
                        province = obj.province || '';
                        city = obj.city || '';
                        area = obj.district || '';
                        getAddressCode();
                        
                    }
                    
                    tableContent += '<div class="bac" onclick="changedAddress('+i+')"  style="padding:1rem;border-bottom:2px solid #ece9e9"><p>'+obj.address+'</p><p style="font-size:0.6rem">'+ detail +'</p></div>';
                }
                $('.choose-div').html(tableContent);
            }
        }

        /*function getAreaInfo(){
            getAddressCode(province,city,area);
        }*/

        //根据省市区 获取对应编码
        function getAddressCode() {

            area_info = province + ' '+ city
            if(area != undefined && area != null && area != ''){
                area_info += ' '+area;
            }
            //将省市区放到对应区域
            var p_id='';
            var c_id='';
            var a_id='';
            if(cityData3 == undefined || cityData3 == null || cityData3 == '' || cityData3.length <=0){
                return;
            }
            for(var i=0; i<cityData3.length; i++){
                var data = cityData3[i];
                if(data.text == province){
                    p_id = data.value
                    $('#province_id').val(data.value);
                    var children = data.children;
                    if(children!=undefined && children != null && children !='' && children.length > 0){
                        for(var j = 0;j<children.length;j++){
                            if(children[j].text == city){
                                c_id = children[j].value;
                                $('#city_id').val(children[j].value);
                                children = children[j].children;
                                if(children!=undefined && children != null && children !='' && children.length > 0){
                                    for(var m =0;m<children.length;m++){
                                        if(children[m].text == area){
                                            a_id = children[m].value;
                                            $('#area_id').val(children[m].value);
                                            getAreaInfo(a_id);
                                            break;
                                        }else if(m >= children.length -1){
                                            $('#area_id').val(c_id);
                                            getAreaInfo(c_id);
                                        }
                                    }
                                }
                                break;
                            }else if(j >= children.length-1){
                                $('#city_id').val(p_id);
                                $('#area_id').val(p_id);
                                getAreaInfo(p_id);
                            
                            }
                        }
                    }
                    break;
                }
            }
        }

        function getAreaInfo(a_id){
            //将此省市区放到select中
            $('#area').citys({
                code:a_id,
                required: false,
                nodata: 'disabled',
                onChange: function (data) {
                    $('#area_info').val(data['province'] + ' ' + data['city'] + ' ' + data['area']);
                }
            });
        }


        function changedAddress(i){

            var obj = search_nearPost[i];
            console.log(obj);
            var address = obj.name?obj.name:obj.title;
            $('#position_address').val(address);
            var latLng = ''
            if(obj.latLng == undefined || obj.latLng == null || obj.latLng == ''){
                latLng = obj.location.lat +','+obj.location.lng;
                lat = obj.location.lat;
                lng = obj.location.lng;
            }else{
                latLng = obj.latLng.lat +','+obj.latLng.lng;
                lat = obj.latLng.lat;
                lng = obj.latLng.lng;
            }
            marker.setMap(null);
            info.setMap(null);
            make_map(lat,lng);
            $('#area_position').val(latLng);
        
            $('.choose-div').hide();
         
        }

    
        function make_map(lat,lng){
            center = new qq.maps.LatLng(lat, lng);
            map.setCenter(center);
            marker = new qq.maps.Marker({
                map:map,
                position: center
            });
            //添加信息窗口
            info = new qq.maps.InfoWindow({
                map: map
            });
            //获取标记的可拖动属性
            info.open();
            info.setContent('<p style="color:  #25bdef">用户地址</p>');
            info.setPosition(marker.getPosition());
        }


        $('#position_address').bind("input propertychange",function(event){
            var infos = $('.position_address').val();
            if(infos != undefined && infos != null && infos != ''){
                
                var url = 'https://apis.map.qq.com/ws/place/v1/suggestion/?region='+region+'&keyword='+infos+'&output=jsonp&key=RHHBZ-K26W6-CPISS-ENGXG-HVCRS-QJFQT';
                url = encodeURI(url);
                $.ajax({
                    type:"get",
                    url: url,
                    dataType: "JSONP",
                    jsonp: 'callback',
                    success: function (res) {
                        search_nearPost = res.data;
                        console.log(search_nearPost);
                    
                        make_address_list(search_nearPost,1);
                        $('.choose-div').show();
                        
                    },
                    error: function (res,reson) {
                        mui.toast('请求失败');
                    }
                });
            
            }
        })
    </script>
@endsection